import SparkMD5 from 'spark-md5';

export function fileMd5(file) {
    if (file instanceof Uint8Array) {
        return new Promise((resolve, reject) => {
            const spark = new SparkMD5.ArrayBuffer();
            spark.append(file);
            const md5 = spark.end();
            resolve(md5);
        })
    }
  return new Promise((resolve, reject) => {
    const chunkSize = 1024 * 1024; // 每次读取1MB
    const chunks = Math.ceil(file.size / chunkSize);
    let currentChunk = 0;
    const spark = new SparkMD5.ArrayBuffer();
    const fileReader = new FileReader();

    fileReader.onload = (e) => {
      spark.append(e.target.result); // 追加分片
      currentChunk++;

      if (currentChunk < chunks) {
        loadNext();
      } else {
        const md5 = spark.end();
        resolve(md5);
      }
    };

    fileReader.onerror = () => reject('文件读取出错');

    function loadNext() {
      const start = currentChunk * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      fileReader.readAsArrayBuffer(file.slice(start, end));
    }

    loadNext();
  });
}

export function strMd5(str) {
  return SparkMD5.hash(str);
}